package com.sdutcm.Shiro;

/*
 *@Author Yan
 *@Create 2019-08-28 10:56
 */



import com.sdutcm.Mapper.RealmMapper;
import com.sdutcm.Service.ServiceImpl.RealmServiceImpl;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.eis.SessionDAO;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.subject.support.DefaultSubjectContext;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;

public class UserRealm extends AuthorizingRealm {

    @Autowired
    private RealmServiceImpl realmService;
//    private SessionDAO sessionDAO;
    private RealmMapper realmMapper;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection Token) {
        System.out.println("执行授权操作");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        Subject subject = SecurityUtils.getSubject();

        User user = (User) subject.getPrincipal();
        User userDB = realmMapper.findByUsername(user.getUsername());
        for (Role role : realmMapper.selectRoleList(userDB.getUsername())){
             info.setStringPermissions((Set<String>) role);
        }
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken Token) throws AuthenticationException {
        System.out.println("执行认证操作");
//        从网页端获取用户名
        String username = (String) Token.getPrincipal();
        User user = realmService.findByUsername(username);

//            防止多端登录
//        Collection<Session> sessions = sessionDAO.getActiveSessions();
//        for (Session session: sessions){
//            String loginedUsername = String.valueOf(session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY));
//            if (username.equals(loginedUsername)){
//                System.out.println(loginedUsername);
//                session.setTimeout(0);
//                break;
//            }
//        }


        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user,user.getPassword(),getName());
        if (user.getStatus() == 0){
            throw new  AuthenticationException("该账号已被禁用");
        }
        return info;
    }
}
